#!/usr/bin/env python

import rospy
from std_msgs.msg import String
from PIL import Image
import os, glob

class listener():
	def __init__(self):
		rospy.init_node('ch_map',anonymous=True)	

		self.getmap_read = rospy.Subscriber("read_upmap",String,self.callback)
                self.upmap_pub = rospy.Publisher('read_getmap',String,queue_size=1)

	def callback(self,data):
    		rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    		if(data.data=="1"):
			self.batch_image('/home/liang/map/oldmap', '/home/liang/map/newmap')
			self.upmap_pub.publish("1")

	def batch_image(self,in_dir, out_dir):
	    if not os.path.exists(out_dir):
		print(out_dir, 'is not existed.')
		os.mkdir(out_dir)
	    
	    if not os.path.exists(in_dir):
		print(in_dir, 'is not existed.')
		return -1
	    
	    for files in glob.glob(in_dir+'/*.pgm'):
		#filename = os.path.split(files)
		
		out_file = 'newmap.jpg'
		# print(filepath,',',filename, ',', out_file)
		im = Image.open(files)
		new_path = os.path.join(out_dir, out_file)
		print(new_path)
		im.save(os.path.join(out_dir, out_file)) 
		#self.upmap_pub.publish("1")
 
if __name__=='__main__':
	try:
    		listener()
		rospy.spin()
	except rospy.ROSInterruptException:
        	rospy.loginfo("ch_map finished.") 
